import aiohttp
import requests

from .common_enum import *
from conf.config import REPORT_URL


# 异步请求工具
async def async_request_tool(case):
	session = aiohttp.ClientSession()
	expect_type = case["expect_type"]
	expect = case["expect"]

	async with session.request(url=case["url"], method=case["method"], headers=case["headers"], data=case["params"]) as response:
		# 状态码
		if expect_type == 'CODE':
			result = response.status
		# 响应数据
		elif expect_type == Response.CONTENT:
			result = await response.read()
		elif expect_type == Response.COOKIES:
			result = response.cookies
		elif expect_type == Response.HEADERS:
			result = response.headers
		elif expect_type == Response.ENCODING:
			result = response.get_encoding()
		elif expect_type == Response.HISTORY:
			result = response.history
		#  请求参数
		elif expect_type == Response.REQUEST:
			result = response.request_info
		# 超时时间
		elif expect_type == Response.ELAPSED:
			result = response.release()
		else:
			result = response.text

		if str(result) == expect:
			actual = True
		else:
			actual = False

		await async_report(case['case_id'], case['task_id'], expect, actual, result)
	await session.close()


# 异步上报结果
async def async_report(case_id, task_id, expect, actual, response_data):
	if isinstance(response_data, bytes):
		response_data = str(response_data, 'utf-8')

	report = {
		"case_id": case_id,
		"task_id": task_id,
		"expect": expect,
		"actual": actual,
		"response_data": response_data
	}
	async with aiohttp.ClientSession() as session:
		await session.post(url=REPORT_URL, data=report)


def request_tool(case):
	expect_type = case["expect_type"]
	expect = case["expect"]

	response = requests.request(url=case["url"], method=case["method"], headers=case["headers"], data=case["params"])
	# 状态码
	if expect_type == 'CODE':
		result = response.content
	# 响应数据
	elif expect_type == Response.CONTENT:
		result = response.content
	elif expect_type == Response.COOKIES:
		result = response.cookies
	elif expect_type == Response.HEADERS:
		result = response.headers
	elif expect_type == Response.ENCODING:
		result = response.encoding
	elif expect_type == Response.HISTORY:
		result = response.history
	#  请求参数
	elif expect_type == Response.REQUEST:
		result = response.request
	# 超时时间
	elif expect_type == Response.ELAPSED:
		result = response.elapsed
	else:
		result = response.text

	if str(result) == expect:
		actual = True
	else:
		actual = False
	print(result)
	return result
